package com.flower.controller;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.flower.pojo.User;
import com.flower.service.IUserService;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户模块
 */

@Controller
public class UserController {

	@Resource(name = "userService")
	private IUserService iUserService;

	/**
	 * 用户注册
	 */
	@RequestMapping("/register.do")
	public String register(User user, Model model) throws Exception {
		List<User> users = iUserService.findAllUsers();
		for (User u : users) {
			if (u.getUsername().equals(user.getUsername())) {
				model.addAttribute("msg", "用户名已被注册");
				return "register";
			} else if (u.getEmail().equals(user.getEmail())) {
				model.addAttribute("msg", "邮箱已被注册");
				return "register";
			} else if (u.getTelephone().equals(user.getTelephone())) {
				model.addAttribute("msg", "手机号已被注册");
				return "register";
			}
		}

		user.setCount(10000);
		int row = iUserService.register(user);
		if (row > 0) {
			return "login";
		}

		return "register";
	}

	/**
	 * 用户登录
	 */
	@RequestMapping(value = "/login.do")
	public String login(User user, HttpServletRequest request, Model model)
			throws Exception {
		User userDB = iUserService.login(user);
		// 1.获取radio的值，判断用户的身份
		// 2.判断用户是否为空
		String status = request.getParameter("status");
		if ("vip".equals(status)) {
			if (userDB != null) {
				// 创建HttpSession封装user对象
				request.getSession().setAttribute("USER", userDB);
				// 获取Cookie,若无，则重定向到default.jsp页面
				Cookie[] cookies = request.getCookies();
				String url = "/default.jsp";
				for(int i=0; i < cookies.length && cookies != null; i++){
					if(cookies[i].getName().equals("URL")){
						url = cookies[i].getValue();
					}
				}
				return "redirect:" + url;
			}else {
				model.addAttribute("msg", "此用户不存在，请重新输入！");
				// 使用重定向，msg信息会在地址栏上显示
				return "login";
			}
		}else {
			return "forward:/adminToLogin.do";
		}
	}
	
	

	/**
	 * 用户退出
	 */
	@RequestMapping("/logout.do")
	public String logout(HttpServletRequest request) {
		// 销毁当前的HttpSession对象
		request.getSession().invalidate();
		// 重定向到default.jsp页面
		return "redirect:/default.jsp";
	}
}
